package xyz.ibenben.zhongdian.common.configure;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.common.intercepter.AddPrincipalToSessionFilter;
import xyz.ibenben.zhongdian.common.shiro.LimitRetryHashedMatcher;
import xyz.ibenben.zhongdian.common.shiro.MyShiroRealm;
import xyz.ibenben.zhongdian.system.entity.sys.SysResources;
import xyz.ibenben.zhongdian.system.mapper.sys.SysResourcesMapper;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Shiro配置
 *
 * @author chenjian
 * @since 2017年10月18日下午5:17:22
 */
@Configuration
@AutoConfigureAfter(ShiroLifecycleBeanPostProcessorConfig.class)
public class ShiroConfig {
    /* 系统资源服务 这里使用mapper不能使用service否则cache失效*/
    @Autowired(required = false)
    private SysResourcesMapper sysResourcesMapper;

    /* Redis主机 */
    @Value("${spring.redis.host}")
    private String host;

    /* Redis端口 */
    @Value("${spring.redis.port}")
    private int port;

    /* Redis超时时间 */
    @Value("${spring.redis.timeout}")
    private int timeout;

    /**
     * ShiroDialect，为了在thymeleaf里使用shiro的标签的bean
     *
     * @return 返回值
     */
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

    /**
     * ShiroFilterFactoryBean 处理拦截资源文件问题。
     * 注意：单独一个ShiroFilterFactoryBean配置是或报错的，因为在
     * 初始化ShiroFilterFactoryBean的时候需要注入：SecurityManager
     * <p>
     * Filter Chain定义说明
     * 1、一个URL可以配置多个Filter，使用逗号分隔
     * 2、当设置多个过滤器时，全部验证通过，才视为通过
     * 3、部分过滤器可指定参数，如perms，roles
     *
     * @param securityManager 参数
     * @return 返回值
     */
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //获取filters
        Map<String, Filter> filters = shiroFilterFactoryBean.getFilters();
        //rememberMe存session过滤器
        filters.put("addPrincipal", addPrincipalToSessionFilter());

        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/");
        //未授权界面
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        //拦截器.
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        //在每个可以使用RememberMe功能进行访问的url上面都添加这个自定义的Filter
        filterChainDefinitionMap.put("/", "user, addPrincipal");
        //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/static/**", "anon");

        //这里设置调过权限判断的地址
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/regist", "anon");
        filterChainDefinitionMap.put("/pwdBack", "anon");
        filterChainDefinitionMap.put("/getVerifyCode", "anon");
        filterChainDefinitionMap.put("/emailActivate", "anon");
        filterChainDefinitionMap.put("/resetPassword", "anon");
        filterChainDefinitionMap.put("/sendMessage", "anon");
        filterChainDefinitionMap.put("/getMessage", "anon");

        //<!-- 过滤链定义，从上向下顺序执行，一般将 /**放在最为下边 -->:这是一个坑呢，一不小心代码就不好使了
        //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
        //自定义加载权限资源关系
        List<SysResources> resourcesList = sysResourcesMapper.selectList(new QueryWrapper<>());
        for (SysResources resources : resourcesList) {
            if (StringUtils.isNotEmpty(resources.getResUrl())) {
                String permission = "perms[" + resources.getResUrl() + "]";
                filterChainDefinitionMap.put(resources.getResUrl(), permission);
            }
        }
        filterChainDefinitionMap.put("/index", "user, addPrincipal");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    /**
     * 添加过滤器
     *
     * @return 返回值
     */
    @Bean
    public AddPrincipalToSessionFilter addPrincipalToSessionFilter() {
        return new AddPrincipalToSessionFilter();
    }

    /**
     * 安全管理
     *
     * @return 返回值
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //设置realm.
        securityManager.setRealm(myShiroRealm());
//		正式环境打开此注释 securityManager.setCacheManager(cacheManager())
        // 自定义session管理 使用redis
        securityManager.setSessionManager(sessionManager());
        securityManager.setRememberMeManager(rememberMeManager());
        return securityManager;
    }

    /**
     * 密码加密
     *
     * @return 返回值
     */
    @Bean
    public MyShiroRealm myShiroRealm() {
        //自定义类
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        myShiroRealm.setAuthorizationCachingEnabled(false);
        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myShiroRealm;
    }

    /**
     * 凭证匹配器
     * （由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
     * 所以我们需要修改下doGetAuthenticationInfo中的代码）
     *
     * @return 返回值
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new LimitRetryHashedMatcher();
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        hashedCredentialsMatcher.setHashAlgorithmName(Constants.ALGORITHMNAME);
        //散列算法:这里使用MD5算法
        hashedCredentialsMatcher.setHashIterations(Constants.HASHITERATIONS);
        //散列的次数，比如散列两次，相当于 md5(md5(""))
        return hashedCredentialsMatcher;
    }

    /**
     * 开启shiro aop注解支持.
     * 使用代理方式;所以需要开启代码支持
     *
     * @param securityManager 参数
     * @return 返回值
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        //授权处理
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * RedisSessionDAO shiro sessionDao层的实现 通过redis
     * 使用的是shiro-redis开源插件
     *
     * @return 返回值
     */
    @Bean
    public RedisSessionDAO redisSessionDAO() {
        //RedisSessionDAO shiro sessionDao层的实现 通过redis
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        redisSessionDAO.setKeyPrefix("Redis:Session:Shiro:");
        return redisSessionDAO;
    }

    /**
     * 配置shiro redisManager
     * 使用的是shiro-redis开源插件
     *
     * @return 返回值
     */
    private RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(port);
        // 配置缓存过期时间
        redisManager.setExpire(1800);
        redisManager.setTimeout(timeout);
        // redisManager.setPassword(password)
        return redisManager;
    }

    /**
     * shiro session的管理
     *
     * @return 返回值
     */
    @Bean
    public DefaultWebSessionManager sessionManager() {
        //session的管理
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionDAO(redisSessionDAO());
        sessionManager.setCacheManager(new RedisCacheManager());
        sessionManager.setGlobalSessionTimeout(3600000);
        sessionManager.setDeleteInvalidSessions(true);
        sessionManager.setSessionValidationInterval(3600000);
        sessionManager.setSessionIdCookie(sessionIdCookie());
        return sessionManager;
    }

    /**
     * Session和Cookie设置
     *
     * @return 返回值
     */
    @Bean
    public SimpleCookie sessionIdCookie() {
        //Session和Cookie设置
        SimpleCookie simpleCookie = new SimpleCookie("SHRIOSESSIONID");
        simpleCookie.setHttpOnly(true);
        simpleCookie.setMaxAge(-1);
        return simpleCookie;
    }

    /**
     * 记住我的Cookie
     *
     * @return 返回值
     */
    @Bean
    public SimpleCookie rememberMeCookie() {
        // 这个参数是cookie的名称，对应前端的checkbox的name = rememberMe
        SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
        simpleCookie.setHttpOnly(true);
        // 记住我cookie生效时间30天 ,单位秒
        simpleCookie.setMaxAge(259200);
        return simpleCookie;
    }

    /**
     * cookie管理对象
     *
     * @return 返回值
     */
    @Bean
    public CookieRememberMeManager rememberMeManager() {
        //cookie管理对象
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());
        cookieRememberMeManager.setCipherKey(Base64.decode("2AvVhdsgUs0FSA3SDFAdag=="));
        return cookieRememberMeManager;
    }

    /**
     * 代理设置
     *
     * @return 返回值
     */
    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        //代理设置
        DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
        daap.setProxyTargetClass(true);
        return daap;
    }

    /**
     * 授权
     *
     * @return 返回值
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
        //授权
        AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
        aasa.setSecurityManager(securityManager());
        return aasa;
    }

}
